#include "widget.h"

#include "fsmp_board/fsmpCamera.h"
#include <QFileInfo>
#include <QVBoxLayout>
#include <QRandomGenerator>

void Widget::InitW4(QWidget *parent)
{
    QWidget* body = paneBody(parent);
    if (!body) return;

    auto v = qobject_cast<QVBoxLayout*>(body->layout());
    if (!v) {
        v = new QVBoxLayout(body);
        v->setContentsMargins(0,0,0,0);

        v->setSpacing(0);
        body->setLayout(v);
    }
    while (v->count() > 0) {
        if (auto it = v->takeAt(0)) {
            if (auto w = it->widget()) w->deleteLater();
            delete it;
        }
    }

    m_camView = new QLabel(body);
    m_camView->setAlignment(Qt::AlignCenter);
    m_camView->setStyleSheet("background: transparent;"); // ✅ 背景透明
    // 关键：不要用 setScaledContents(true)（在 Wayland 上容易触发协议错误）
    m_camView->setScaledContents(false);
    // 用“Preferred”避免去挤外层网格；w4 大小仍由你的 8 宫格决定
    m_camView->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    v->addWidget(m_camView, 1);

    // 启动摄像头线程（保持你的参数）
    if (m_camera) { m_camera->quit(); m_camera->wait(); m_camera->deleteLater(); m_camera = nullptr; }
    m_camera = new fsmpCamera("/dev/video1", 640, 480, this);
    connect(m_camera, &fsmpCamera::pixReady, this, &Widget::onCamFrame, Qt::QueuedConnection);
    m_camera->setPixDelay(50 * 1000);
    m_camera->start();
}


void Widget::onCamFrame(const QImage& img)
{
    if (!m_camView || img.isNull()) return;

    m_lastFrame = img;

    const QSize area = m_camView->contentsRect().size();
    if (area.width() <= 0 || area.height() <= 0) return;

    // —— 优先左右铺满：按目标宽度等比放大 —— //
    const double s = double(area.width()) / double(img.width());
    const int nw = area.width();
    const int nh = int(std::round(img.height() * s));

    QImage scaled = img.scaled(nw, nh, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    // 若高度超出，做上下居中裁剪；否则保留下方/上方的透明留白（背景透明）
    QPixmap px;
    if (nh > area.height()) {
        const int y = (nh - area.height()) / 2;
        px = QPixmap::fromImage(scaled.copy(0, y, area.width(), area.height()));
    } else {
        // 高度不足：生成一个透明画布，把图像垂直居中贴上去
        QImage canvas(area, QImage::Format_ARGB32_Premultiplied);
        canvas.fill(Qt::transparent);
        QPainter p(&canvas);
        const int y = (area.height() - nh) / 2;
        p.drawImage(QPoint(0, y), scaled);
        p.end();
        px = QPixmap::fromImage(canvas);
    }

    m_camView->setPixmap(px);
}

void Widget::resizeEvent(QResizeEvent *e)
{
    QWidget::resizeEvent(e);

    if (!m_camView || m_lastFrame.isNull()) return;

    const QSize area = m_camView->contentsRect().size();
    if (area.width() <= 0 || area.height() <= 0) return;

    // 与 onCamFrame 同样的“优先左右铺满 + 可能裁剪”逻辑
    const double s = double(area.width()) / double(m_lastFrame.width());
    const int nw = area.width();
    const int nh = int(std::round(m_lastFrame.height() * s));

    QImage scaled = m_lastFrame.scaled(nw, nh, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    QPixmap px;
    if (nh > area.height()) {
        const int y = (nh - area.height()) / 2;
        px = QPixmap::fromImage(scaled.copy(0, y, area.width(), area.height()));
    } else {
        QImage canvas(area, QImage::Format_ARGB32_Premultiplied);
        canvas.fill(Qt::transparent);
        QPainter p(&canvas);
        const int y = (area.height() - nh) / 2;
        p.drawImage(QPoint(0, y), scaled);
        p.end();
        px = QPixmap::fromImage(canvas);
    }

    m_camView->setPixmap(px);
}
